package com.abing.permissionsys.utils;

import com.abing.permissionsys.entity.vo.ComboBoxVO;
import com.abing.permissionsys.enums.DeptEnums;

import java.lang.reflect.Field;
import java.util.*;

public class DictionaryUtils {



    public static <T extends Enum<?>> List<ComboBoxVO> putEnum(String valueField, String nameField, T... enums)
    {
        List<T> enumValues = Arrays.asList(enums);
        return getComboBox(enumValues, valueField, nameField);
    }
    public static <T extends Enum<?>> List<ComboBoxVO> putEnum(T... enums)
    {
        List<T> enumValues = Arrays.asList(enums);
        return getComboBox(enumValues, "index", "name");
    }


    /**
     * 利用反射获取指定字段的值，并构建ComboBoxVO
     * @Author WeiXiaowei
     * @CreateDate 2018年6月5日下午6:31:31
     */
    public static <T extends Object> List<ComboBoxVO> getComboBox(List<T> list, String valueProperty, String nameProperty)
    {
        Class<?> clazz = list.get(0).getClass();
        List<ComboBoxVO> cbs = new ArrayList<>();
        try
        {
            Field valueField = clazz.getDeclaredField(valueProperty);
            valueField.setAccessible(true);
            Field nameField = clazz.getDeclaredField(nameProperty);
            nameField.setAccessible(true);
            for(Object obj : list)
            {
                ComboBoxVO cb = new ComboBoxVO();
                cb.setValue("" + valueField.get(obj));
                cb.setName("" + nameField.get(obj));
                cbs.add(cb);
            }
        }
        catch(NoSuchFieldException | SecurityException e)
        {
            throw new RuntimeException(clazz.getName() + "不存在" + valueProperty + "、" + nameProperty + "属性", e);
        }
        catch(IllegalArgumentException | IllegalAccessException e)
        {
            throw new RuntimeException(clazz.getName() + "获取" + valueProperty + "、" + nameProperty + "属性值失败", e);
        }
        return cbs;
    }
}
